﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace DambachMulti.DataStructures
{
	public class MultiArray<T> : IList<T>
	{
		List<T>				list		= null; //the inner list we work with
		EqualityComparer<T>	comparer	= EqualityComparer<T>.Default;

		public MultiArray()
		{
			list = new List<T>(); //empty constructor
		}
		public MultiArray( int initCapacity ) {			
			list = new List<T>( initCapacity );
		}
		public IEnumerator<T> GetEnumerator()
		{
			return list.GetEnumerator();
		}
		IEnumerator IEnumerable.GetEnumerator() {
			return list.GetEnumerator();
		}

		public void Add( T item ) {
			list.Add( item );
		}

		public void Clear() {
			list.Clear();
		}

		public bool Contains( T item )
		{
			//capable of parallel searching
			bool foundIt = false;
			Multi.SmartPooledFor( 0, list.Count, 1, delegate( int i ) {
				if( item == null ) { //resharper is complaining about a possible comparison with value type...If this seems like it is a problem I'll change it...but for now it seems fine.
					if ( list[i] == null ) //no locking should be necessary...since different indices are being looked up...If it is a problem, its .Net fault
						return true;
					//else
					return false; //second statement, the below brace is needed
				}
				else
					if ( this.comparer.Equals( list[i], item) ){
						foundIt = true;
						return true; //exits early
					}
					else //by using the internal list, we are slightly more efficient
						return false;				
				}, Environment.ProcessorCount ); //optimized for fully utilizing the processors available
			return foundIt;
		}

		public void CopyTo(T[] array, int arrayIndex) //hmmmm, sequential seems better unless its a complex struct type T we have been given
		{
			list.CopyTo( array, arrayIndex );
		}

		public bool Remove(T item)
		{
			return list.Remove( item );
		}

		public int Count
		{
			get { return list.Count; }
		}

		public bool IsReadOnly //wtf????
		{			
			get { return false; }
		}

		/// <summary>
		/// TODO: make multicore...right now just test contains
		/// </summary>
		/// <param name="item"></param>
		/// <returns></returns>
		public int IndexOf( T item )
		{
			return list.IndexOf( item );
		}

		public void Insert(int index, T item)
		{
			list.Insert( index, item );
		}

		public void RemoveAt(int index)
		{
			list.RemoveAt( index );
		}

		public T this[int index]
		{
			get { return list[index]; }
			set { list[index] = value; }
		}
	}
}
